package download.itydl.com.sinlethread.services;

import android.app.Service;
import android.content.Intent;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;

import java.io.File;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

import download.itydl.com.sinlethread.bean.FileInfo;

/**
 * 文件下载服务
 *
 * @author howard
 */
public class DownLoadService extends Service {

    /**
     * Activity往Service传递Intent设置key
     */
    public static final String FILE_INFO = "fileInfo";
    /**
     * 开始下载
     */
    public static final String START = "START";
    /**
     * 暂停下载
     */
    public static final String PAUSE = "STOP";
    private static final String TAG = "yangdaolong";
    /**
     * 下载路径
     */
    public static final String DOWNLOAD_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/downloads/";
    /**
     * 更新UI
     */
    public static final String ACTION_UPDATE = "ACTION_UPDATE";

    private DownloadTask downloadTask;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // fileInfo实例携带了文件大小信息
            FileInfo fileInfo = (FileInfo) msg.obj;
            Log.e(TAG, "handleMessage" + fileInfo.toString());
            // 在这开启下载
            downloadTask = new DownloadTask(fileInfo, DownLoadService.this);
            downloadTask.downLoad();
        }
    };

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (START.equals(intent.getAction())) {
            FileInfo fileInfo = (FileInfo) intent.getSerializableExtra(FILE_INFO);
            Log.e(TAG, "onStartCommand: ACTION_START-" + fileInfo.toString());
            // 服务创建，立即开启获取服务器文件大小的线程
            new InitThread(fileInfo).start();
        } else if (PAUSE.equals(intent.getAction())) {
            FileInfo fileInfo = (FileInfo) intent.getSerializableExtra(FILE_INFO);
            Log.e(TAG, "onStartCommand: ACTION_STOP-" + fileInfo.toString());
            if(downloadTask != null){
                downloadTask.isPause = true;
            }

        }
        return super.onStartCommand(intent, flags, startId);

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * 初始化操作
     * 获取服务端下载文件的大小、本地创建同等大小的文件
     */
    class InitThread extends Thread {

        FileInfo fileInfo;

        public InitThread(FileInfo fileInfo) {
            this.fileInfo = fileInfo;
        }

        @Override
        public void run() {
            HttpURLConnection conn = null;
            RandomAccessFile raf = null;
            try {
                // 请求网络
                URL url = new URL(fileInfo.getUrl());
                conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(5000);
                int length = -1;
                int responseCode = conn.getResponseCode();
                Log.e(TAG, "ResponseCode==" + responseCode);
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    //获取文件长度
                    length = conn.getContentLength();
                    Log.e(TAG, "length==" + length);
                }
                if (length < 0) {
                    Log.e(TAG, "length==0");
                    return;
                }
                // 创建本地文件
                File dir = new File(DOWNLOAD_PATH);
                if (!dir.exists()) {
                    dir.mkdir();
                }
                File file = new File(dir, fileInfo.getFileName());

                // 设置文件大小
                raf = new RandomAccessFile(file, "rwd");
                raf.setLength(length);
                fileInfo.setLength(length);

                Log.e(TAG, "Is Sucess ：" + fileInfo.toString());

                Message message = mHandler.obtainMessage();
                message.obj = fileInfo;
                message.sendToTarget();

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (conn != null && raf != null) {
                        conn.disconnect();
                        raf.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
